# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution(object):
    def __init__(self):
        self.current_tree = TreeNode()

    def buildTree(self, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: Optional[TreeNode]
        """

        self.loop(inorder, postorder, self.current_tree)
        return self.current_tree

    def loop(self, inorder, postorder, current_tree):
        inpoint = postorder[-1]
        current_tree.val = inpoint

        in_index = inorder.index(inpoint)

        inorder_left = inorder[:in_index]
        inorder_right = inorder[in_index + 1:]

        postorder_left = postorder[:in_index]
        postorder_right = postorder[in_index:-1]

        if inorder_left:
            current_tree.left = TreeNode()
            self.loop(inorder_left, postorder_left, current_tree.left)

        if inorder_right:
            current_tree.right = TreeNode()
            self.loop(inorder_right, postorder_right, current_tree.right)
